package com.wz.netty;

import java.net.SocketAddress;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

public class ClientWriteHandler extends ChannelOutboundHandlerAdapter{

	@Override
	public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
		System.out.println("cli-outbound-bind");
		super.bind(ctx, localAddress, promise);
	}

	@Override
	public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
		System.out.println("cli-outbound-close");
		super.close(ctx, promise);
	}

	@Override
	public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
			ChannelPromise promise) throws Exception {
		System.out.println("cli-outbound-connect");
		super.connect(ctx, remoteAddress, localAddress, promise);
	}

	@Override
	public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
		System.out.println("cli-outbound-deregister");
		super.deregister(ctx, promise);
	}

	@Override
	public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
		System.out.println("cli-outbound-disconnect");
		super.disconnect(ctx, promise);
	}

	@Override
	public void flush(ChannelHandlerContext ctx) throws Exception {
		System.out.println("cli-outbound-flush");
		super.flush(ctx);
	}

	@Override
	public void read(ChannelHandlerContext ctx) throws Exception {
		System.out.println("cli-outbound-read");
		super.read(ctx);
	}

	@Override
	public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		System.out.println("cli-outbound-write");
    	final ChannelFuture f = ctx.writeAndFlush((ByteBuf)msg);
    	f.addListener(new ChannelFutureListener() {
			
			public void operationComplete(ChannelFuture arg0) throws Exception {
				ctx.close();
			}
		});
	}
	
}